package san.web.m;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import san.entity.m.Product;
import san.entity.m.Supplier;
import san.entity.m.Variety;
import san.service.m.ProductService;
import san.service.m.SupplierService;
import san.service.m.VarietyService;

import com.utils.Page;
import com.web.struts2.CRUDSupportAction;

@ParentPackage("default")
@Results( { @Result(name = "reload", location = "product.shtml", type = "redirect") })
public class ProductAction extends CRUDSupportAction {
	/**
	 * 自动生成ProductAction类.
	 */
	private static final long serialVersionUID = 3862953416083377388L;
	@Autowired
	private ProductService productService;
	@Autowired
	private VarietyService varietyService;
	@Autowired
	private SupplierService supplierService;
	private Page<Product> page = new Page<Product>(10);// 每页10条记录
	private Product product;
	private List<Variety> varietys;
	private List<Supplier> suppliers;
	
	@Override
	protected void prepareModel() throws Exception {
		if (product != null && StringUtils.isNotBlank(product.getId())) {
			product = productService.get(product.getId());
		} else {
			if (StringUtils.isNotBlank(getId())) {
				product = productService.get(getId());
			} else {
				product = new Product();
			}
		}
	}

	@Override
	public String delete() throws Exception {
		if (StringUtils.isNotBlank(getId())) {
			productService.delete(getId());
		}
		return RELOAD;
	}

	@Override
	public String input() throws Exception {
		suppliers=supplierService.getAll();
		varietys = varietyService.getAll();
		return "input";
	}

	@Override
	public String list() throws Exception {
		setPage(productService.getAll(page));
		return SUCCESS;
	}

	@SuppressWarnings("finally")
	@Override
	public String save() throws Exception {
		try {
			productService.save(product);
			addActionMessage("保存成功!");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError("保存失败!");
		} finally {
			return RELOAD;
		}
	}

	public Page<Product> getPage() {
		return page;
	}

	public void setPage(Page<Product> page) {
		this.page = page;
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public List<Variety> getVarietys() {
		return varietys;
	}

	public void setVarietys(List<Variety> varietys) {
		this.varietys = varietys;
	}

	public List<Supplier> getSuppliers() {
		return suppliers;
	}

	public void setSuppliers(List<Supplier> suppliers) {
		this.suppliers = suppliers;
	}

}
